package com.aimaterials.resource.service.impl;

import com.aimaterials.common.annotation.DataScope;
import com.aimaterials.common.constant.UserConstants;
import com.aimaterials.common.core.domain.TreeSelect;
import com.aimaterials.common.core.domain.entity.SysRole;
import com.aimaterials.common.exception.CustomException;
import com.aimaterials.common.utils.StringUtils;
import com.aimaterials.resource.domain.ComSpecialty;
import com.aimaterials.resource.mapper.ComSpecialtyMapper;
import com.aimaterials.resource.service.IComSpecialtytService;
import com.aimaterials.system.mapper.SysRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 专业管理 服务实现
 *
 * @author DaemonSu
 */
@Service
public class ComSpecialtyServiceImpl implements IComSpecialtytService
{
    @Autowired
    private ComSpecialtyMapper specialtyMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    /**
     * 查询专业管理数据
     *
     * @param dept 专业信息
     * @return 专业信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<ComSpecialty> selectDeptList(ComSpecialty dept)
    {
        return specialtyMapper.selectDeptList(dept);
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 专业列表
     * @return 树结构列表
     */
    @Override
    public List<ComSpecialty> buildDeptTree(List<ComSpecialty> depts)
    {
        List<ComSpecialty> returnList = new ArrayList<ComSpecialty>();
        List<Long> tempList = new ArrayList<Long>();
        for (ComSpecialty dept : depts)
        {
            tempList.add(dept.getSpecialtyId());
        }
        for (Iterator<ComSpecialty> iterator = depts.iterator(); iterator.hasNext();)
        {
            ComSpecialty dept = (ComSpecialty) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId()))
            {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 专业列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<ComSpecialty> depts)
    {
//        List<ComSpecialty> deptTrees = buildDeptTree(depts);
//        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
        return  null;
    }

    /**
     * 根据角色ID查询专业树信息
     *
     * @param roleId 角色ID
     * @return 选中专业列表
     */
    @Override
    public List<Integer> selectDeptListByRoleId(Long roleId)
    {
        SysRole role = roleMapper.selectRoleById(roleId);
        return specialtyMapper.selectDeptListByRoleId(roleId, role.isDeptCheckStrictly());
    }

    /**
     * 根据专业ID查询信息
     *
     * @param deptId 专业ID
     * @return 专业信息
     */
    @Override
    public ComSpecialty selectDeptById(Long deptId)
    {
        return specialtyMapper.selectDeptById(deptId);
    }

    /**
     * 根据ID查询所有子专业（正常状态）
     *
     * @param deptId 专业ID
     * @return 子专业数
     */
    @Override
    public int selectNormalChildrenDeptById(Long deptId)
    {
        return specialtyMapper.selectNormalChildrenDeptById(deptId);
    }

    /**
     * 是否存在子节点
     *
     * @param deptId 专业ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(Long deptId)
    {
        int result = specialtyMapper.hasChildByDeptId(deptId);
        return result > 0 ? true : false;
    }

    /**
     * 查询专业是否存在用户
     *
     * @param deptId 专业ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId)
    {
        int result = specialtyMapper.checkDeptExistUser(deptId);
        return result > 0 ? true : false;
    }

    /**
     * 校验专业名称是否唯一
     *
     * @param dept 专业信息
     * @return 结果
     */
    @Override
    public String checkDeptNameUnique(ComSpecialty dept)
    {
        Long deptId = StringUtils.isNull(dept.getSpecialtyId()) ? -1L : dept.getSpecialtyId();
        ComSpecialty info = specialtyMapper.checkDeptNameUnique(dept.getSpecialtyName(), dept.getParentId());
        if (StringUtils.isNotNull(info) && info.getSpecialtyId().longValue() != deptId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增保存专业信息
     *
     * @param dept 专业信息
     * @return 结果
     */
    @Override
    public int insertDept(ComSpecialty dept)
    {
        ComSpecialty info = specialtyMapper.selectDeptById(dept.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if(info!=null){
            if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
            {
                throw new CustomException("专业停用，不允许新增");
            }
            dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        }


        return specialtyMapper.insertDept(dept);
    }

    /**
     * 修改保存专业信息
     *
     * @param dept 专业信息
     * @return 结果
     */
    @Override
    public int updateDept(ComSpecialty dept)
    {
        ComSpecialty newParentDept = specialtyMapper.selectDeptById(dept.getParentId());
        ComSpecialty oldDept = specialtyMapper.selectDeptById(dept.getSpecialtyId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept))
        {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getSpecialtyId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getSpecialtyId(), newAncestors, oldAncestors);
        }
        int result = specialtyMapper.updateDept(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()))
        {
            // 如果该专业是启用状态，则启用该专业的所有上级专业
            updateParentDeptStatus(dept);
        }
        return result;
    }

    /**
     * 修改该专业的父级专业状态
     *
     * @param dept 当前专业
     */
    private void updateParentDeptStatus(ComSpecialty dept)
    {
        String updateBy = dept.getUpdateBy();
        dept = specialtyMapper.selectDeptById(dept.getSpecialtyId());
        dept.setUpdateBy(updateBy);
        specialtyMapper.updateDeptStatus(dept);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId 被修改的专业ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors)
    {
        List<ComSpecialty> children = specialtyMapper.selectChildrenDeptById(deptId);
        for (ComSpecialty child : children)
        {
            child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            specialtyMapper.updateDeptChildren(children);
        }
    }

    /**
     * 删除专业管理信息
     *
     * @param deptId 专业ID
     * @return 结果
     */
    @Override
    public int deleteDeptById(Long deptId)
    {
        return specialtyMapper.deleteDeptById(deptId);
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<ComSpecialty> list, ComSpecialty t)
    {
        // 得到子节点列表
        List<ComSpecialty> childList = getChildList(list, t);
        t.setChildren(childList);
        for (ComSpecialty tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<ComSpecialty> getChildList(List<ComSpecialty> list, ComSpecialty t)
    {
        List<ComSpecialty> tlist = new ArrayList<ComSpecialty>();
        Iterator<ComSpecialty> it = list.iterator();
        while (it.hasNext())
        {
            ComSpecialty n = (ComSpecialty) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getSpecialtyId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<ComSpecialty> list, ComSpecialty t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }
}
